from netdevsdk import *
import time


class DevClass:
    def __init__(self):
        self.egsSdk = self.load_sdk()  # 加载sdk库
        self.iUserID = -1  # 登录句柄

    def load_sdk(self):
        # egs_sdk = None
        #
        # try:
        #     egs_sdk = load_library(net_sdk_dll_path)
        # except Exception as e:
        #     print("动态库[{}]加载失败:{}".format(net_sdk_dll_path, e))
        # return egs_sdk
        egs_sdk = None
        try:
            egs_sdk = load_library(net_sdk_dll_path)

            # NETDEV_Login_V30
            egs_sdk.NETDEV_Login_V30.restype = c_void_p
            egs_sdk.NETDEV_Login_V30.argtypes = [POINTER(NETDEV_DEVICE_LOGIN_INFO_S), POINTER(NETDEV_SELOG_INFO_S)]

            # NETDEV_GetFileByTime
            egs_sdk.NETDEV_GetFileByTime.restype = c_void_p
            egs_sdk.NETDEV_GetFileByTime.argtypes = [c_void_p, POINTER(NETDEV_PLAYBACKCOND_S), c_char_p, c_int]

            # NETDEV_Logout
            egs_sdk.NETDEV_Logout.restype = c_int
            egs_sdk.NETDEV_Logout.argtypes = [c_void_p]

            # NETDEV_PlayBackControl
            egs_sdk.NETDEV_PlayBackControl.restype = c_int
            egs_sdk.NETDEV_PlayBackControl.argtypes = [c_void_p, c_int, c_void_p]

        except Exception as e:
            print("动态库[{}]加载失败:{}".format(net_sdk_dll_path, e))
        return egs_sdk


    def sdk_init(self):
        res = self.egsSdk.NETDEV_Init()
        if res != 0:
            print("初始化sdk")

    def login(self, ip, port, username, password):
        login_info = NETDEV_DEVICE_LOGIN_INFO_S()
        login_info.szIPAddr = ip
        login_info.dwPort = port
        login_info.szUserName = username
        login_info.szPassword = password
        login_info.dwLoginProto = 0
        login_info.dwDeviceType = 0

        se_log_info = NETDEV_SELOG_INFO_S()
        self.iUserID = self.egsSdk.NETDEV_Login_V30(pointer(login_info), pointer(se_log_info))
        if login_info == 0:
            print("登陆失败，错误码：", self.egsSdk.NETDEV_GetLastError())
        return login_info

    def download(self, channel_id, begin_time, end_time, save_filename):

        dInfo = NETDEV_VIDEO_CHL_DETAIL_INFO_S()
        bRet = self.egsSdk.NETDEV_QueryVideoChlDetailList(self.iUserID, c_int32(128), dInfo)
        print("bRet", bRet)

        # 初始化结构体
        playback_cond = NETDEV_PLAYBACKCOND_S()

        # 填充结构体参数
        playback_cond.dwChannelID = channel_id
        playback_cond.tBeginTime = begin_time  # UNIX时间戳，单位秒或毫秒（根据SDK要求）
        playback_cond.tEndTime = end_time  # UNIX时间戳，单位秒或毫秒（根据SDK要求）
        playback_cond.dwLinkMode = 1
        playback_cond.dwDownloadSpeed = 2  # 下载倍速

        get_file = self.egsSdk.NETDEV_GetFileByTime(self.iUserID, byref(playback_cond), save_filename.encode('utf-8'), 0)
        if get_file == 0:
            return
        time.sleep(1)

        play_time = c_int64(0)
        self.egsSdk.NETDEV_PlayBackControl(get_file, 3, byref(play_time))

        while play_time.value < end_time:
            # 获取下载进度
            self.egsSdk.NETDEV_PlayBackControl(get_file, 3, byref(play_time))
            print("当前下载到：%.2f%%"%((play_time.value-begin_time)/(end_time-begin_time)*100))
            time.sleep(1)

    def logout(self):
        res = self.egsSdk.NETDEV_Logout(self.iUserID)
        if res == 0:
            print("登出失败，错误码：", self.egsSdk.NETDEV_GetLastError())

    def sdk_cleanup(self):
        res = self.egsSdk.NETDEV_Cleanup()
        if res != 0:
            print("释放sdk")

    def __del__(self):
        self.logout()
        self.sdk_cleanup()


if __name__ == '__main__':
    dev = DevClass()
    dev.sdk_init()

    # 输入参数
    ip = b"192.168.1.30"
    port = 80
    username = b"admin"
    password = b"Nanjing@8625"
    dev.login(ip, port, username, password)

    channel_id = 1
    begin_time = 1748931710
    end_time = 1748931718
    save_filename = "./video/{}.mp4".format(begin_time)
    dev.download(channel_id, begin_time, end_time, save_filename)
